package com.yswy.common.annotation;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;

/**
 * 日期传参格式校验
 * @author yanwei
 * @since 2024/1/11 15:21
 */
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = DateFormat.DateFormatValidator.class)
public @interface DateFormat {
    String message() default "日期格式错误";
 
    String format() default "yyyy-MM-dd";
 
    Class<?>[] groups() default {};
 
    Class<? extends Payload>[] payload() default {};

    class DateFormatValidator implements ConstraintValidator<DateFormat, String> {

        private DateFormat dateFormat;

        @Override
        public void initialize(DateFormat dateFormat) {
            this.dateFormat = dateFormat;
        }

        @Override
        public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
            String format = dateFormat.format();
            if (format.equals("yyyy-MM")) {
                DateTimeFormatter dtf1 = new DateTimeFormatterBuilder()
                        .appendPattern(format)
                        .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
                        .toFormatter();
                try {
                    LocalDate.parse(s, dtf1);
                } catch (Exception e) {
                    return false;
                }
            } else {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
                try {
                    simpleDateFormat.parse(s);
                } catch (Exception e) {
                    return false;
                }
            }
            return true;
        }
    }
}